<style lang="less" scoped>
  .page__wrapper {
    width: 100%;
    height: 100%;
  }
</style>

<template>
  <div class="page__wrapper">
    <simple-table :table-column="tableColumn" :table-data="tableData" :table-page-info="tablePageInfo" :table-data-count="tableDataTotalCount" @page-info-change="handlePageInfoChange">
      <template slot="searchSection">
        <simple-form v-model="searchModel" :form-field="searchFormField">
          <template slot="tableOperation">
            <el-button @click="handleDataSearch">{{$t('operation.search')}}</el-button>
            <el-button type="primary" @click="handleAddClick" v-if="actionList.indexOf('add')>=0">{{$t('operation.create')}}</el-button>
          </template>
        </simple-form>
      </template>
      <template slot-scope="scope" slot="sex">
        <!-- {{$getDictLabel({type: 'data_status', value: scope.row.status})}} -->
        {{ $getDictLabel({type: '性别', value: scope.row.sex })}}
      </template>
      <template slot-scope="scope" slot="status">
        {{ $getDictLabel({type: '账号状态', value: scope.row.status })}}
      </template>

      <template slot-scope="scope" slot="roleids">
        {{ scope.row.roleids | roleFilter(roleList)}}
      </template>
      <template slot-scope="scope" slot="companyid">
        {{ scope.row.companyid | orgFilter(orgList)}}
      </template>
      <template slot="operation" slot-scope="scope">
        <el-button circle icon="el-icon-search" :title="$t('operation.view')" @click="handleViewClick(scope.row)"></el-button>
        <el-button v-if="actionList.indexOf('edit')>=0" circle icon="el-icon-edit" :title="$t('operation.edit')" @click="handleEditClick(scope.row)"></el-button>
        <el-button v-if="actionList.indexOf('del')>=0" @click="deleteRecord(scope.row)" circle icon="el-icon-delete" :title="$t('operation.delete')"></el-button>
      </template>
    </simple-table>
    <detail-dialog :show-flag.sync="isShowDetailDialog" :detail-data="rowData" :ext-data="{roleList, orgList, sys_mid}" :view-flag="isViewFlag"></detail-dialog>
  </div>
</template>
<script>
import Axios from 'axios'
/** 混入分页信息及数据总数信息 */
import pageMixins from '@/components/base/simple-table/page-mixins'
import detailDialog from './detail'
const BASEURL = {
  list: `/Web/SysAdmin/ajax.html?sys_method=GetList&sys_objName=V_SYS_UserList&sys_tableName=Sys_User`,
  delete: '/Web/SysAdmin/ajax.html?sys_method=Delete&sys_objName=Sys_User',
  getCombobox: '/Web/SysAdmin/ajax.html?sys_method=GetCombobox',
  getInitConfig: '/Web/SysAdmin/ajax.html?sys_method=GetInitConfig'
}
export default {
  name: 'system_user',
  mixins: [pageMixins],
  components: { detailDialog },
  data () {
    return {
      searchModel: {},
      /** 表格数据 */
      tableData: [],
      rowData: {},
      /** 是否显示详情页 dialog */
      isShowDetailDialog: false,
      /** 是否为查看数据 */
      isViewFlag: false,

      roleList: [],
      orgList: [],
      actionList: [],
      sys_mid: ''
    }
  },
  filters: {
    roleFilter (value, roleList) {
      if (!value) return ''
      let valueArr = value.split(',')
      let resultStr = []
      valueArr.forEach(valueItem => {
        let cacheRole = roleList.filter(roleItem => roleItem.value === valueItem)
        if (cacheRole.length > 0) resultStr.push(cacheRole[0].text)
      })
      return resultStr.join()
    },
    orgFilter (value, orgList) {
      if (!value) return ''
      let valueArr = value.split(',')
      let resultStr = []
      valueArr.forEach(valueItem => {
        let cacheOrg = orgList.filter(orgItem => orgItem.value === valueItem)
        if (cacheOrg.length > 0) resultStr.push(cacheOrg[0].text)
      })
      return resultStr.join()
    }
  },
  computed: {
    searchFormField () {
      return [
        { prop: 'username', label: this.$t('system_user.username'), type: 'Input', component: { clearable: true } },
        { prop: 'fullname', label: this.$t('system_user.fullname'), type: 'Input', component: { clearable: true } },
        // { prop: 'sex', label: this.$t('system_user.sex'), type: 'Select', component: { optionList: this.$getDictList('性别'), clearable: true } },
        { prop: 'status', label: this.$t('system_user.status'), type: 'Select', component: { optionList: this.$getDictList('账号状态'), clearable: true } },
        { slotName: 'tableOperation', col: { md: 6, style: { textAlign: 'right' } }, labelWidth: '0' }
      ]
    },
    tableColumn () {
      return [
        { prop: 'username', label: this.$t('system_user.username'), width: 100 },
        { prop: 'fullname', label: this.$t('system_user.fullname'), width: 120 },
        // { prop: 'password', label: this.$t('system_user.password'), width: 150 },
        // { prop: 'pwdexpiredtime', label: this.$t('system_user.pwdexpiredtime'), width: 150 },
        { prop: 'sex', label: this.$t('system_user.sex'), width: 80, slotName: 'sex' },
        { prop: 'phone', label: this.$t('system_user.phone'), width: 120 },
        { prop: 'status', label: this.$t('system_user.status'), width: 80, slotName: 'status' },
        { prop: 'logincount', label: this.$t('system_user.logincount'), width: 80 },
        { prop: 'lastlogintime', label: this.$t('system_user.lastlogintime'), width: 150 },
        { prop: 'lastloginip', label: this.$t('system_user.lastloginip'), width: 100 },
        { prop: 'email', label: this.$t('system_user.email'), minWidth: 120 },
        { prop: 'roleids', label: this.$t('system_user.roleids'), width: 150, slotName: 'roleids' },
        { prop: 'companyid', label: this.$t('system_user.companyid'), width: 150, slotName: 'companyid' },
        { label: this.$t('field.operation'), slotName: 'operation', width: 100, fixed: 'right' }
      ]
    }
  },
  /**
   * 注入到子组件
   */
  provide () {
    return { handleDataSearch: this.handleDataSearch }
  },
  methods: {
    handleDataSearch () {
      let params = Object.assign({}, this.tablePageInfo, { sys_mid: this.sys_mid, sort: 'createtime', order: 'desc' }, { sys_search: this.searchModel })

      let loadingFlag = this.$loading({ fullscreen: false, target: this.$el, text: this.$t('tip.systemLoading') })
      this.$axios
        .post(BASEURL.list, params)
        .then(resp => {
          this.tableData = resp.rows
          this.tableDataTotalCount = resp.total
        })
        .finally(() => {
          loadingFlag.close()
        })
    },

    handleInitData () {
      let configLoadingFlag = this.$loading({ fullscreen: false, target: this.$el, text: this.$t('tip.systemLoading') })
      this.$axios
        .post(BASEURL.getInitConfig, {})
        .then(resp => {
          // 设置 actionList及sys_mid
          this.actionList = resp.actionKeys.split(',')

          this.sys_mid = resp.mid
          /** 设置列表及涉及主数据请求参数 */
          let params = Object.assign({}, this.tablePageInfo, { sys_mid: this.sys_mid, sort: 'createtime', order: 'desc' })
          let comboParams = { sys_json: JSON.stringify([{ ObjName: 'C_SYS_Role' }, { ObjName: 'C_SYS_Org' }]) }
          let loadingFlag = this.$loading({ fullscreen: false, target: this.$el, text: this.$t('tip.systemLoading') })

          Axios.all([
            this.$axios.post(BASEURL.list, params),
            this.$axios.post(BASEURL.getCombobox, comboParams)
          ])
            .then(Axios.spread((pageData, comboData) => {
              this.tableData = pageData.rows
              this.tableDataTotalCount = pageData.total

              this.roleList = comboData.C_SYS_Role
              this.orgList = comboData.C_SYS_Org
            }))
            .finally(() => {
              loadingFlag.close()
            })
        })
        .finally(() => {
          configLoadingFlag.close()
        })
    },

    handleAddClick () {
      this.rowData = {}
      this.isViewFlag = false
      this.isShowDetailDialog = true
    },
    handleViewClick (row) {
      this.rowData = this.$_.cloneDeep(row)
      this.isViewFlag = true
      this.isShowDetailDialog = true
    },
    handleEditClick (row) {
      this.rowData = this.$_.cloneDeep(row)
      this.isViewFlag = false
      this.isShowDetailDialog = true
    },
    deleteRecord (row) {
      this.$msgbox({
        title: this.$t('tip.warning'),
        message: this.$t('tip.confirmDelete'),
        type: 'warning',
        showCancelButton: true,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            let params = { id: row.userid, idField: 'userid', sys_mid: this.sys_mid }
            this.$axios
              .post(BASEURL.delete, params)
              .then(resp => {
                this.$message({ type: 'success', message: this.$t('tip.deleteSuccess') })
                done()
              })
              .finally(() => {
                instance.confirmButtonLoading = false
              })
          } else done()
        }
      })
        .then(() => {
          /** 如果本页面中只有一条数据 */
          /** 手动触发 simple-table 组件中的 watch，从而调用 mixins 中的请求数据方法 */
          if (this.tableData.length === 1) {
            this.tablePageInfo.page--
          } else {
            this.handleDataSearch()
          }
        })
    }
  },
  mounted () {
    this.handleInitData()
  }
}
</script>
